package md.frolov.bible.model;

import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import md.frolov.bible.Constants;
import md.frolov.bible.initializers.CustomXMLParser;

public class Chapter implements IStructure, IViewLabelProvider, IURLProvider{
	private String id;
	private String name;
	private Book book;
	
	private Chapter(){
		
	}
	
	public Chapter(String id){
		this.id = id;
		
	}
	
	public Book getBook(){
		return book;
	}
	
	public void setParent(Book parent){
		this.book = parent;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public Object[] getChildren() {
		return null;
	}

	@Override
	public Object getParent() {
		return book;
	}

	@Override
	public boolean hasChildren() {
		return false;
	}

	@Override
	public String getText() {
		return getName();
	}

	public String getUrl() {
		return book.getModule().getUrl()+getId();
//		return book.getUrl()+"."+getLocalId();
	}

	public String getId() {
		return id;
	}

	public String getLocalId() {
		String[] list = id.split("\\.");
		return list[list.length-1];
	}
	
//	public String getContents(){
//		try{
//			SAXParserFactory spf = SAXParserFactory.newInstance();
//			SAXParser sp = spf.newSAXParser();
//			long time1 = System.currentTimeMillis();
//			XMLHandler h = new XMLHandler();
//			sp.parse(new InputSource(new InputStreamReader(new FileInputStream(book.getModule().getFile()),"UTF-8")), h);
//			System.out.println("Parsing time: "+((System.currentTimeMillis()-time1)/1000.0));
//			System.out.println("successfully parsed");
//			return h.getString();
//		} catch(FileNotFoundException e){
//			e.printStackTrace();
//		} catch (UnsupportedEncodingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (SAXException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (ParserConfigurationException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		return "Something's wrong";
//	}
	
	public Verse[] getVerses(){
		try{
			CustomXMLParser cp = new CustomXMLParser(getBook().getModule().getFile());
			return cp.getChapter(getId());
		} catch (Exception e){
			e.printStackTrace();
		}
		return new Verse[]{};
//		try{
//			SAXParserFactory spf = SAXParserFactory.newInstance();
//			SAXParser sp = spf.newSAXParser();
//			long time1 = System.currentTimeMillis();
//			XMLHandler h = new XMLHandler();
//			sp.parse(new InputSource(new InputStreamReader(new FileInputStream(book.getModule().getFile()),"UTF-8")), h);
//			System.out.println("Parsing time: "+((System.currentTimeMillis()-time1)/1000.0));
//			System.out.println("successfully parsed");
//			System.out.println("The size in here here: "+h.getList().size());
//			return (Verse[]) h.getList().toArray(new Verse[]{});
//		} catch(FileNotFoundException e){
//			e.printStackTrace();
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//		} catch (SAXException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		} catch (ParserConfigurationException e) {
//			e.printStackTrace();
//		}
//		return new Verse[]{};
	}

	private class XMLHandler extends DefaultHandler{
		StringBuffer sb = new StringBuffer();
		List<Verse> list = new ArrayList<Verse>();
		
		String lastId=null;
		String lastLocalId=null;
		String lastContents = null;
		
		boolean startVerse = false;
		boolean start = false;
		@Override
		public void startElement(String uri, String localName, String name,	Attributes attributes) throws SAXException {
			if(name.equals(Constants.XML_CHAPTER_TAG))
				if(getId().equals(attributes.getValue("id"))) {
					start = true;
					return;
				}
			if(!start) return;
			if(name.equals(Constants.XML_VERSE_TAG)){
				lastId = attributes.getValue(Constants.XML_ATTRIBUTE_ID);
				lastLocalId = attributes.getValue(Constants.XML_ATTRIBUTE_VERSE_LOCAL_ID);
				
				startVerse = true;
			}
		}
	
		@Override
		public void endElement(String uri, String localName, String name)
				throws SAXException {
			if(!start) return;
			
			if(name.equals(Constants.XML_VERSE_TAG)){
				if(startVerse)list.add(new Verse(lastId,lastLocalId,lastContents,Chapter.this));
				
				startVerse = false;
				
				return;
			}
			
			if(name.equals(Constants.XML_CHAPTER_TAG)){
				start = false;
				return;
			}
		}
	
		@Override
		public void characters(char[] ch, int start, int length)throws SAXException {
			if(!startVerse) return;
			lastContents = new String(ch, start, length);
		}
		
		public List<Verse> getList(){
			return list;
		}
	}

	public Chapter previousChapter() {
		List<Chapter> chps = book.getChapters();
		int ix = chps.indexOf(this);
		if(ix==0){
			List<Book> books = book.getModule().getBooks();
			int iix = books.indexOf(book);
			if(iix==0) iix=books.size()-1;
				else iix--;
			return books.get(iix).getLastChapter();
		}
		return chps.get(ix-1);
	}
	
	public Chapter nextChapter(){
		List<Chapter> chps = book.getChapters();
		int ix = chps.indexOf(this);
		if(ix==chps.size()-1){
			List<Book> books = book.getModule().getBooks();
			int iix = books.indexOf(book);
			if(iix==books.size()-1) iix=0;
				else iix++;
			return books.get(iix).getFirstChapter();
		}
		return chps.get(ix+1);
	}
}
